/*
 * Copyright (c) 2022 The red-star Project
 *
 * Licensed under the Apache License, version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.inyourcode.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.inyourcode.excel.model.ExcelReaderListener;
import com.inyourcode.excel.model.SheetDataModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 读取excel数据
 * @author JackLei
 */
public class ExcelMonther {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelMonther.class);

    /**
     * 读取excel数据
     * @param excelRootPath
     * @return
     */
    public static Map<String, SheetDataModel> scanExcelData(String excelRootPath) {
        Map<String, SheetDataModel> sheetDataModelMap =  new HashMap<>();
        File pathFile = new File(excelRootPath);
        scanExcelData(pathFile, sheetDataModelMap);
        return sheetDataModelMap;
    }

    /**
     * 读取exel数据
     * @param rootPathFile excel文件的根目录
     */
    private static void scanExcelData(File rootPathFile, Map<String, SheetDataModel> sheetDataModelMap) {
        if (!rootPathFile.isDirectory()) {
            if ((!rootPathFile.getName().endsWith("xlsx") && !rootPathFile.getName().endsWith("xls")) || rootPathFile.getName().contains("._")) {
                LOGGER.warn("This rootPathFile [{}] is ignored", rootPathFile.getName());
            } else {
                ExcelReaderListener excelReaderListener = new ExcelReaderListener();
                ExcelReader excelReader = EasyExcel.read(rootPathFile, excelReaderListener).doReadAll();

                sheetDataModelMap.putAll(excelReaderListener.getSheetDataModelMap());
                excelReader.finish();
            }
        } else {
            for (File fileTemp : rootPathFile.listFiles()) {
                scanExcelData(fileTemp, sheetDataModelMap);
            }
        }
    }

}
